package com.partner.boot.service.impl;

import com.partner.boot.entity.Permission;
import com.partner.boot.mapper.PermissionMapper;
import com.partner.boot.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小熊
 * @since 2023-03-15
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Override
    public List<Permission> tree() {
        
        // 查出所有数据
        List<Permission> allData = list();

        // 2 递归实现   从第一级开始往下递归获取树
        return childrenTree(null, allData);
    }

    // 递归生成树
    private List<Permission> childrenTree(Integer pid, List<Permission> allData) {
        // childrenTree 构建父子级关系的树的 返回的为list
        // 筛选 目录 菜单 按钮  目录的pid可能为空，目录里面套目录
        List<Permission> list = new ArrayList<>();
        for (Permission permission : allData) {
            // null, 一级
            if (Objects.equals(permission.getPid(), pid)) {
                list.add(permission);
                // 递归调用， 摘取二级节点、三级、四级...
                List<Permission> childrenTree = childrenTree(permission.getId(), allData);
                permission.setChildren(childrenTree);
            }
        }
        return list;
    }
}
